#include "ring_buffer_bytes.h"

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <thread>
#include <chrono>


RingBufferBytes buffer(32000);
FILE* fpout;

void fun1()  //初始化构造函数
{
    std::cout << "Thread " << 1 << " executing" << std::endl;
    int num = 1;
    while(1)
    {
        if(num>4096) num = 1;
        num += 5;
        char buf[4096];
        int ret = buffer.read(buf, num);
        if(ret<0){
            printf("read error, ret = %d\n", ret);
            break;
        }else if(0==ret){
            //std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }else{
        //printf("read ret = %d\n", ret);
            fwrite(buf, 1, ret, fpout);
        }
    }
    fclose(fpout);
    //std::cout << "Thread " << n << " executing\n";
    //n += 10;
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    std::cout << "Thread " << 1 << " exit" << std::endl;
}

void fun2()  //初始化构造函数
{
    std::cout << "Thread " << 1 << " executing" << std::endl;
    int num = 1;
    while(1)
    {
        if(num>4096) num = 1;
        num += 5;
        char buf[4096];
        int ret = buffer.read_chunk(buf, 4096);
        if(ret<0){
            printf("read error, ret = %d\n", ret);
            break;
        }else if(0==ret){
            //std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }else{
            printf("read ret = %d\n", ret);
            fwrite(buf, 1, ret, fpout);
        }
    }
    fclose(fpout);
    //std::cout << "Thread " << n << " executing\n";
    //n += 10;
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    std::cout << "Thread " << 1 << " exit" << std::endl;
}

void test_wirte(int num)
{
    char data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int ret = buffer.write((const char*)data, num);
    printf("write ret = %d\n", ret);
}

void test_read(int num)
{
    char buf[10];
    int ret = buffer.read(buf, num);
    printf("read ret = %d\n", ret);
    for(int i = 0; i< ret; i++)
    {
        printf("%d ", buf[i]);
    }
    printf("\n");
}

int main(int argc, char *argv[])
{
    std::thread t1(fun2);

    FILE* fp = fopen("main.o", "rb");
    fpout = fopen("out.o", "wb");

    char data[4096];
    int read_size = 0;
    for(int i=1; i<100000 ; i++)
    {
        read_size = i;
        int length = fread(data, 1, read_size, fp);
        //printf("fread len = %d\n", length);
        if(length<=0) break;
        int sz = 0;
        while(length>sz)
        {
            int ret = buffer.write(data+sz, length-sz);
            if(0==ret)
            {
                //std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
            sz += ret;
            //printf("write ret = %d, (%d/%d)\n", ret, sz, length);
        }
    }
    buffer.close();
    fclose(fp);

    t1.join();

    return 0;
}

